<?php
namespace Frieza\Modules\Mcn\Controllers;

use App\Pockets\GridDataModel as pGridDataModel;
use App\Http\Controllers\Controller;
use Doraemon\model\Mcn\McnBasicInfos;
use Doraemon\model\Mcn\McnBrands;
use Doraemon\model\Mcn\McnGoods;
use Doraemon\model\Mcn\McnPlatforms;
use Doraemon\model\Member;
use Doraemon\service\position\PositionApi;
use Doraemon\tools\Area;
use Doraemon\tools\Log;
use Doraemon\service\McnService;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;

/**
 * @deprecated
 * 第一代mcn用户筛选 @pankeyi 产品确认没人用了。
 */
class McnController extends Controller
{
    public function list(Request $request, Content $content)
    {
        $params = $request->input();
        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);

        $province_id = $params['province'] ?? 0;
        $good_type = $params['good_type'] ?? 0;
        $search = [];
        if (isset($params['uid']) && $params['uid']) {
            $search['uid'] = $params['uid'];
        }
        if (isset($params['nick']) && $params['nick']) {
            $search['nick'] = $params['nick'];
        }
        if (isset($params['gender']) && is_numeric($params['gender'])) {
            $search['gender'] = $params['gender'];
        }
        if (isset($params['province']) && $params['province']) {
            $search['province'] = Area::locationId2location($params['province']);
        }
        if (isset($params['city']) && $params['city']) {
            $search['city'] = Area::locationId2location($params['city']);
        }
        $key_list = ['space','fans_num','action_count_beliked_befavor','article_num','blank_num','video_num','note_num'];
        foreach ($key_list as $key) {
            if (isset($params[$key]) && $params[$key]) {
                if (isset($params[$key]['start']) && is_numeric($params[$key]['start'])) {
                    $search["{$key}[>=]"] = $params[$key]['start'];
                }
                if (isset($params[$key]['end']) && is_numeric($params[$key]['end'])) {
                    $search["{$key}[<=]"] = $params[$key]['end'];
                }
            }
        }
        if (isset($params['expertise_area']) && $params['expertise_area']) {
            $search['expertise_area'] = $params['expertise_area'];
        }
        $work_search_key = '';
        if (isset($params['brand']) && $params['brand']) {
            $work_search_key .= $params['brand'] . '-';
        }
        if (isset($params['modus']) && $params['modus']) {
            if (!$work_search_key) {
                $work_search_key .= '-' . $params['modus'] . '-';
            } else {
                $work_search_key .= $params['modus'] . '-';
            }
        }
        if (isset($params['price']) && $params['price']) {
            if (!$work_search_key) {
                $work_search_key .= '-' . $params['price'];
            } else {
                $work_search_key .= $params['price'];
            }
        }
        if ($work_search_key) {
            $search['work_info'] = $work_search_key;
        }
        $good_search_key = '';
        if (isset($params['good_type']) && $params['good_type']) {
            $good_search_key .= McnGoods::TYPE_DESC[$params['good_type']] . '-';
        }
        if (isset($params['good_id']) && $params['good_id']) {
            if (!$good_search_key) {
                $good_search_key .= '-' . McnGoods::getGoodNameByID($params['good_id']) . '-';
            } else {
                $good_search_key .= McnGoods::getGoodNameByID($params['good_id']) . '-';
            }
        }
        if (isset($params['brand_id']) && $params['brand_id']) {
            if (!$good_search_key) {
                $good_search_key .= '-' . McnBrands::getBrandNameByID($params['brand_id']);
            } else {
                $good_search_key .= McnBrands::getBrandNameByID($params['brand_id']);
            }
        }
        if ($good_search_key) {
            $search['good_info'] = $good_search_key;
        }

        $list = McnService::getKolList($page, $pageSize, $search);

        $gridModel = new pGridDataModel($list['list'], $list['total'], [
            'perPage' => $pageSize
        ]);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel, $province_id, $good_type) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();

                $grid->filter(function($filter) use ($province_id, $good_type) {
                    $filter->disableIdFilter();

                    $filter->column(1/2, function ($filter) use ($good_type) {
                        $filter->equal('uid');
                        $filter->equal('nick', '昵称');
                        $filter->equal('gender', '性别')->radio([0=>'未知', 1=>'男', 2=>'女']);
                        $filter->equal('expertise_area', '擅长领域')->select(McnBasicInfos::EXPERTISE_AREA);
                        $filter->equal('brand', '合作品牌');
                        $filter->equal('modus', '合作形式');
                        $filter->equal('price', '合作费用');
                        $all_goods = $good_type > 0 ? array_column(McnGoods::getGoodListByType($good_type), 'text', 'id') : [];
                        $filter->equal('good_type', '物品分类')->select(McnGoods::TYPE_DESC)->load('good_id', route('mcn.select_goods'));
                        $filter->equal('good_id', '物品')->select($all_goods);
                        $filter->equal('brand_id', '品牌')->select(McnBrands::getBrandInfos());
                    });
                    $filter->column(1/2, function ($filter) use ($province_id)  {
                        $filter->between('space', '房屋面积');
                        $filter->between('fans_num', '粉丝数');
                        $filter->between('action_count_beliked_befavor', '获赞收藏数');
                        $filter->between('article_num', '整屋数');
                        $filter->between('blank_num', '文章数');
                        $filter->between('video_num', '视频数');
                        $filter->between('note_num', '动态数');
                        $all_city = $province_id > 0 ? Area::getLocation($province_id) : [];
                        $top = Area::getLocation();
                        $filter->equal('province', '省')->select($top)->load('city', '/admin/position/area');
                        $filter->equal('city', '市、区')->select($all_city);
                    });

                    $filter->expand();
                });

                $grid->column("uid", 'UID');
                $grid->column("nick", '昵称');
                $grid->column("gender", '性别');
                $grid->column("identity_mark", "标签");
                $grid->column("area", "地区");
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                    $actions->disableEdit();
                    $actions->append('&nbsp;&nbsp;<a class="fa fa-edit" href="/admin/mcn/create/'.$actions->row->uid.'">编辑</a>');
                });
            });

        $tab = new Tab();
        $tab->add('用户列表', $gridList->render(), true);
        $content->row($tab);
        return $content
            ->header('主客用户管理')
            ->description(' ')
            ->breadcrumb(['text' => '用户列表']);
    }

    public function create(Request $request, Content $content, $uid = 0)
    {
        $tab = new Tab();
        $userProfile = PositionApi::getOneUserProfile($uid);
        $user_type = Member::getUserInfoByid('type', ['uid'=>$uid]);

        $userForm = $this->getForm($uid);
        $userForm->display('user_info.uid', 'UID')->default($uid);
        $userForm->display('user_info.nick', '昵称')->default($userProfile['nick']);
        $userForm->display('user_info.area', '地区')->default($userProfile['city']);
        $userForm->display('user_info.device_model', '设备型号')->default($userProfile['device_model']);
        if ($user_type == Member::AUTH_USER_DESIGNER) {
            $userForm->display('user_info.be_bind_article_num', '设计师被绑定的整屋案例的数量')->default($userProfile['be_bind_article_num']);
            $userForm->display('user_info.designer_decorate_basic_package_type', '设计师套餐类型')->default($userProfile['designer_decorate_basic_package_type']);
            $userForm->display('user_info.designer_hierarchy', '设计师分层')->default($userProfile['designer_hierarchy']);
        }
        $userForm->display('user_info.logindays_7', '最近7天登录天数')->default($userProfile['logindays_7']);
        $userForm->display('user_info.last_login_day', '上次登录日期')->default($userProfile['last_login_day']);
        $userForm->display('user_info.user_level', '用户等级分层')->default($userProfile['user_level']);
        $userForm->display('user_info.user_product_level', '用户生产等级标签')->default($userProfile['user_product_level']);
        $userForm->textarea('user_info.address', '地址');
        $userForm->text('user_info.phone', '电话');
        $userForm->text('user_info.wechat', '微信');
        $userForm->date('user_info.birthday', '生日');
        $userForm->radio('user_info.gender', '性别')->options([0=>'未知',1=>'男',2=>'女'])->default(0);
        $userForm->text('user_info.profession', '职业');
        $userForm->text('user_info.wx_group', '所在微信群');
        $userForm->imgUpload('user_info.photo', '照片');

        $houseForm = $this->getForm($uid);
        $houseForm->display('house_info.home_status', '房屋状态')->default($userProfile['home_status']);
        $houseArr = explode(',', $userProfile['house_type']);
        $house_type = $houseArr ? $houseArr[0] . '室' . $houseArr[1] . '厅' . $houseArr[2] . '厨' . $houseArr[3] . '卫' : '';
        $houseForm->display('house_info.house_type', '户型信息')->default($house_type);
        $houseForm->display('house_info.decoration_status', '装修状态')->default($userProfile['decoration_status']);
        $houseForm->number('house_info.house_num', '套数')->min(0)->default(0);
        $houseForm->number('house_info.space', '面积')->min(0)->default(0);
        $houseForm->radio('house_info.kitchen', '厨房')->options([0=>'未知',1=>'开放',2=>'不开放'])->default(0);
        $houseForm->text('house_info.style', '风格');
        $houseForm->radio('house_info.balcony', '阳台')->options([0=>'未知',1=>'开放',2=>'不开放'])->default(0);

        $familyForm = $this->getForm($uid);
        $familyForm->text('family_info.pet', '宠物');
        $familyForm->text('family_info.children', '孩子');
        $familyForm->number('family_info.long_live_num', '常住人数')->min(0)->default(0);
        $familyForm->text('family_info.hobby', '兴趣爱好');

        $dataForm = $this->getForm($uid);
        $dataForm->display('data_info.fans_num', '粉丝数')->default($userProfile['fans_num']);
        $dataForm->display('data_info.like_num', '获赞收藏数')->default($userProfile['action_count_beliked_befavor']);
        $dataForm->multipleSelect('data_info.expertise_area', '擅长领域')->options(McnBasicInfos::EXPERTISE_AREA);
        $dataForm->display('data_info.whole_house_num', '整屋数')->default($userProfile['article_num']);
        $dataForm->display('data_info.article_num', '文章数')->default($userProfile['blank_num']);
        $dataForm->display('data_info.video_num', '视频数')->default($userProfile['video_num']);
        $dataForm->display('data_info.dynamic_num', '动态数')->default($userProfile['note_num']);
        $dataForm->display('data_info.login_time', '最近登录时间')->default($userProfile['last_login_time'] ? date("Y-m-d H:i:s", $userProfile['last_login_time']) : '');
        //$dataForm->display('data_info.publish_time', '最近发布内容时间');
        //$dataForm->display('data_info.publish_frequency', '发布内容频次/周')->default(0);
        $dataForm->display('data_info.product_count_relate_wiki', '绑定wiki数量')->default($userProfile['product_count_relate_wiki']);
        $dataForm->display('data_info.product_time_last_all', '全部最新发布时间')->default($userProfile['product_time_last_all'] ? date("Y-m-d H:i:s", $userProfile['product_time_last_all']) : '');
        $dataForm->display('data_info.product_avg_score', '生产内容平均分')->default($userProfile['product_avg_score']);
        $dataForm->display('data_info.photo_score', '图片得分')->default($userProfile['photo_score']);
        $dataForm->display('data_info.product_tag_1m', '擅长生产标签(月)')->default($userProfile['product_tag_1m']);

        $platformForm = $this->getForm($uid);
        $platformForm->fieldGroup('platform_info', '', function ($form) {
            $form->hidden('id');
            $form->select('platform_id', '平台')->options(McnPlatforms::getPlatformInfos());
            $form->text('link', '链接');
            $form->text('fans_num', '粉丝量');
            $form->number('like_num', '获赞收藏量')->min(0)->default(0);
        });

        $goodForm = $this->getForm($uid);
        $goodForm->fieldGroup('good_info', '', function ($goodForm) {
            $goodForm->hidden('id');
            $goodForm->select('good_type', '类型')->options(McnGoods::TYPE_DESC)->load('good_id', route('mcn.select_goods'));
            $goodForm->select('good_id', '物品')->options(function ($good_id) {
                return McnGoods::getSameTypeGoodListByID($good_id);
            });
            $goodForm->select('brand_id', '品牌')->options(McnBrands::getBrandInfos());
            $goodForm->text('model', '型号');
        });

        $teamworkForm = $this->getForm($uid);
        $teamworkForm->fieldGroup('work_info', '', function ($teamworkForm) {
            $teamworkForm->hidden('id');
            $teamworkForm->text('brand', '合作品牌');
            $teamworkForm->datetime('work_time', '合作时间');
            $teamworkForm->text('product', '合作产品');
            $teamworkForm->number('price', '合作费用')->min(0);
            $teamworkForm->text('modus', '合作形式');
            $teamworkForm->text('link', '发布链接');
        });

        $remarkForm = $this->getForm($uid);
        $remarkForm->textarea('remark', '备注');

        $tab->add('用户信息', $userForm);
        $tab->add('房屋信息', $houseForm);
        $tab->add('家人信息', $familyForm);
        $tab->add('合作背书', $dataForm);
        $tab->add('平台信息', $platformForm);
        $tab->add('物品信息', $goodForm);
        $tab->add('商务合作', $teamworkForm);
        $tab->add('备注', $remarkForm);
        return $content
            ->header('主客用户管理')
            ->description('编辑用户信息')
            ->breadcrumb(['text' => '主客用户管理'])
            ->body($tab);
    }

    private function getForm($uid)
    {
        $row = [];
        if ($uid) {
            $row = McnService::getKolInfo($uid);
        }
        $form = new Form($row);
        $form->disableReset();
        $form->hidden('uid')->default($uid);
        $form->action(url('admin/mcn/save'));

        return $form;
    }

    public function select_goods(Request $request)
    {
       $type_id = $request->get('q');

       return McnGoods::getGoodListByType($type_id);
    }

    public function save(Request $request)
    {
        try {
            $params = $request->all();
            unset($params['_token']);

            $result = McnService::saveInfo($params);
            if ($result) {
                return redirect(url('/admin/mcn/create/'.$params['uid']))->with(compact('success'));
            } else {
                $error = new MessageBag([
                    'title' => '操作失败'
                ]);
                return back()->withInput()->with(compact('error'));
            }
        } catch (\Exception $e) {
            Log::debug($e->getMessage());
            $error = new MessageBag([
                'title' => '操作失败,信息:' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    public function platform_list(Request $request, Content $content)
    {
        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);

        $list = McnService::getPlatformList($page, $pageSize);

        $gridModel = new pGridDataModel($list['list'], $list['total'], [
            'perPage' => $pageSize
        ]);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();
                $grid->disableFilter();
                $grid->disableActions();

                $grid->quickCreate(function (Grid\Tools\QuickCreate $create) {
                    $create->text('platform_name', '平台名称');
                });

                $grid->column("id", 'ID');
                $grid->column("platform_name", '平台名称')->editable();
                $grid->column("addtime", '创建时间')->display(function () {
                    return date("Y-m-d H:i:s", $this->addtime);
                });
                $grid->column("edittime", '更新时间')->display(function () {
                    return date("Y-m-d H:i:s", $this->edittime);
                });
            });

        $tab = new Tab();
        $tab->add('平台列表', $gridList->render(), true);
        $content->row($tab);
        return $content
            ->header('主客平台管理')
            ->description(' ')
            ->breadcrumb(['text' => '平台列表']);
    }

    public function platformSubmit(Request $request, $id = 0)
    {
        try {
            $params = $request->all();
            unset($params['_token']);

            if ($id) {
                $result = McnPlatforms::updateData([$params['name']=>$params['value']], ['id'=>$id]);
            } else {
                $result = McnPlatforms::insertData(['platform_name'=>trim($params['platform_name'])]);
            }

            if ($result) {
                return response()->json([
                    'status' => true,
                    'message' => "操作成功",
                ]);
            } else {
                return response()->json([
                    'status' => false,
                    'message' => "操作失败",
                ]);
            }
        } catch (\Exception $e) {
            Log::debug($e->getMessage());
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }

    public function brand_list(Request $request, Content $content)
    {
        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);

        $list = McnService::getBrandList($page, $pageSize);

        $gridModel = new pGridDataModel($list['list'], $list['total'], [
            'perPage' => $pageSize
        ]);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();
                $grid->disableFilter();
                $grid->disableActions();

                $grid->quickCreate(function (Grid\Tools\QuickCreate $create) {
                    $create->text('brand_name', '品牌名称');
                });

                $grid->column("id", 'ID');
                $grid->column("brand_name", '品牌名称')->editable();
                $grid->column("addtime", '创建时间')->display(function () {
                    return date("Y-m-d H:i:s", $this->addtime);
                });
                $grid->column("edittime", '更新时间')->display(function () {
                    return date("Y-m-d H:i:s", $this->edittime);
                });
            });

        $tab = new Tab();
        $tab->add('品牌列表', $gridList->render(), true);
        $content->row($tab);
        return $content
            ->header('主客品牌管理')
            ->description(' ')
            ->breadcrumb(['text' => '品牌列表']);
    }

    public function brandSubmit(Request $request, $id = 0)
    {
        try {
            $params = $request->all();
            unset($params['_token']);

            if ($id) {
                $result = McnBrands::updateData([$params['name']=>$params['value']], ['id'=>$id]);
            } else {
                $result = McnBrands::insertData(['brand_name'=>trim($params['brand_name'])]);
            }

            if ($result) {
                return response()->json([
                    'status' => true,
                    'message' => "操作成功",
                ]);
            } else {
                return response()->json([
                    'status' => false,
                    'message' => "操作失败",
                ]);
            }
        } catch (\Exception $e) {
            Log::debug($e->getMessage());
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }

    public function good_list(Request $request, Content $content)
    {
        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);

        $list = McnService::getGoodList($page, $pageSize);

        $gridModel = new pGridDataModel($list['list'], $list['total'], [
            'perPage' => $pageSize
        ]);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();
                $grid->disableFilter();
                $grid->disableActions();

                $grid->quickCreate(function (Grid\Tools\QuickCreate $create) {
                    $create->select('good_type', '类型')->options(McnGoods::TYPE_DESC)->required();
                    $create->text('good_name', '物品名称')->required();
                });

                $grid->column("id", 'ID');
                $grid->column("good_type", '类型')->editable('select', McnGoods::TYPE_DESC);
                $grid->column("good_name", '物品名称')->editable();
                $grid->column("addtime", '创建时间')->display(function () {
                    return date("Y-m-d H:i:s", $this->addtime);
                });
                $grid->column("edittime", '更新时间')->display(function () {
                    return date("Y-m-d H:i:s", $this->edittime);
                });
            });

        $tab = new Tab();
        $tab->add('物品列表', $gridList->render(), true);
        $content->row($tab);
        return $content
            ->header('主客物品管理')
            ->description(' ')
            ->breadcrumb(['text' => '物品列表']);
    }

    public function goodSubmit(Request $request, $id = 0)
    {
        try {
            $params = $request->all();
            unset($params['_token']);

            if ($id) {
                $result = McnGoods::updateData([$params['name']=>$params['value']], ['id'=>$id]);
            } else {
                $result = McnGoods::insertData(['good_type'=>$params['good_type'], 'good_name'=>trim($params['good_name'])]);
            }

            if ($result) {
                return response()->json([
                    'status' => true,
                    'message' => "操作成功",
                ]);
            } else {
                return response()->json([
                    'status' => false,
                    'message' => "操作失败",
                ]);
            }
        } catch (\Exception $e) {
            Log::debug($e->getMessage());
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }
}